package com.panda.web.controller.commons;

import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.panda.common.core.controller.BaseController;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

@RestController
@RequestMapping("/web/chat")
public class ChatController extends BaseController {
    private final Generation generation;

    @Value("${ai.api.key}")
    private String apiKey;

    public ChatController(Generation generation) {
        this.generation = generation;
    }

    @PostMapping(value = "/ai")
    public ResponseEntity<String> send(@RequestBody String content) {
        try {
            // 用户与模型的对话历史。list中的每个元素形式为{"role":角色, "content": 内容}。
            List<Message> messages = Arrays.asList(
                    Message.builder().role(Role.USER.getValue()).content(content).build()
            );

            GenerationParam param = GenerationParam.builder()
                    // 指定用于对话的通义千问模型名
                    .model("qwen-turbo")
                    .messages(messages)
                    .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                    // 生成过程中核采样方法概率阈值，例如，取值为0.8时，仅保留概率加起来大于等于0.8的最可能token的最小集合作为候选集。
                    // 取值范围为（0,1.0)，取值越大，生成的随机性越高；取值越低，生成的确定性越高。
                    .topP(0.8)
                    // 阿里云控制台DASHSCOPE获取的api-key
                    .apiKey(apiKey)
                    // 启用互联网搜索，模型会将搜索结果作为文本生成过程中的参考信息，但模型会基于其内部逻辑“自行判断”是否使用互联网搜索结果。
                    .enableSearch(true)
                    .build();

            GenerationResult generationResult = generation.call(param);
            return new ResponseEntity<>(generationResult.getOutput().getChoices().get(0).getMessage().getContent(), HttpStatus.OK);
        } catch (NoApiKeyException e) {
            return new ResponseEntity<>("API Key 未设置或无效", HttpStatus.BAD_REQUEST);
        } catch (InputRequiredException e) {
            return new ResponseEntity<>("输入内容不能为空", HttpStatus.BAD_REQUEST);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>("网络异常", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }





    }
